package cn.johnyu;

import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import java.io.IOException;

public class ElasticsearchDemo {

    public static void main(String[] args) {
        // 创建 Elasticsearch 客户端
        try (RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")))) {

            // 创建并发送一个 Index 请求
            IndexRequest indexRequest = new IndexRequest("my_index").id("1")
                    .source("{\"field\": \"value\"}", XContentType.JSON);
            IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
            System.out.println("Index Response: " + indexResponse.toString());

            // 创建并发送一个 Search 请求
            SearchRequest searchRequest = new SearchRequest("my_index");
            searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            // 打印搜索结果
            System.out.println("Search Response: " + searchResponse.toString());
            for (SearchHit hit : searchResponse.getHits().getHits()) {
                System.out.println(hit.getSourceAsString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
